<template>
  <div :style="{ width: containerWidth }" class="tinymce-container fullscreen">
    <el-upload
      class="imgBox"
      :limit="1"
      action="https://jsonplaceholder.typicode.com/posts/"
      :file-list="fileList"
      :http-request="handleUploadImg"
      :on-remove="handleRemove"
    >
      <!-- <i class="el-icon-plus" /> -->
      <el-button style="margin-bottom: 10px" size="small" type="primary"
        >点击上传本地图片</el-button
      >
    </el-upload>
    <!-- <editor  v-model="value"  /> -->
    <editor
      :id="tinymceId"
      v-model="value"
      :init="init"
      class="tinymce-textarea"
    />
  </div>
</template>

<script>
// 引入基础文件：
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver'
import 'tinymce/plugins/image' // 插入上传图片插件
import 'tinymce/plugins/link' // 插入链接
import 'tinymce/plugins/code' // 插入代码
import 'tinymce/plugins/preview' // 插入预览
import 'tinymce/plugins/advlist' // 插入预览
import 'tinymce/plugins/anchor' // 插入预览
import 'tinymce/plugins/autolink' // 插入预览
import 'tinymce/plugins/autosave' // 插入预览
import 'tinymce/plugins/codesample' // 插入预览
import 'tinymce/plugins/contextmenu' // 插入预览
import 'tinymce/plugins/colorpicker' // 插入预览
import 'tinymce/plugins/directionality' // 插入预览
import 'tinymce/plugins/emoticons' // 插入预览
import 'tinymce/plugins/fullscreen' // 插入预览
import 'tinymce/plugins/hr' // 插入预览
import 'tinymce/plugins/imagetools' // 插入预览
import 'tinymce/plugins/insertdatetime' // 插入预览
import 'tinymce/plugins/lists' // 插入预览
import 'tinymce/plugins/media' // 插入预览
import 'tinymce/plugins/nonbreaking' // 插入预览
import 'tinymce/plugins/noneditable' // 插入预览
import 'tinymce/plugins/pagebreak' // 插入预览
import 'tinymce/plugins/textcolor' // 插入预览
import 'tinymce/plugins/template' // 插入预览
import 'tinymce/plugins/table' // 插入预览
import 'tinymce/plugins/tabfocus' // 插入预览
import 'tinymce/plugins/spellchecker' // 插入预览
import 'tinymce/plugins/searchreplace' // 插入预览
import 'tinymce/plugins/save' // 插入预览
import 'tinymce/plugins/print' // 插入预览
import 'tinymce/plugins/preview' // 插入预览
import 'tinymce/plugins/paste' // 插入预览
import 'tinymce/plugins/textpattern' // 插入预览
import 'tinymce/plugins/visualblocks' // 插入预览
import 'tinymce/plugins/visualchars' // 插入预览
import 'tinymce/plugins/wordcount' // 插入预览removeformat
// import 'tinymce/plugins/removeformat' //

import Oss from '@/utils/oss'

export default {
  name: 'Tinymce',
  components: {
    Editor
  },
  props: {
    id: {
      type: String,
      default: () => {
        return (
          'vue-tinymce-' +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + '')
        )
      }
    },
    curValue: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      value: this.curValue,
      tinymceId: this.id,
      oss: {},
      fileList: [],
      stsToken: {
        accessKeyId: 'LTAI5tCQiELrNuXxFdf5wyuB',
        accessKeySecret: 'VlsN1KXHj4RV709wAOIHOnzjn9Qbke',
        bucket: 'utopia9527',
        region: 'oss-cn-shanghai'
      },
      init: {
        selector: `#${this.tinymceId}`,
        language_url: '/tinymce/langs/zh_CN.js', // 语言包的路径
        language: 'zh_CN',
        skin_url: '/tinymce/skins/ui/oxide', // skin路径
        height: 500, // 编辑器高度
        branding: false, // 是否禁用“Powered by TinyMCE”
        menubar: true, // 顶部菜单栏显示
        // end_container_on_empty_block: true,
        // body_class: 'panel-body ',
        elementpath: false, // 禁用编辑器底部的状态栏
        paste_data_images: true, // 允许粘贴图像
        plugins: [
          ' anchor autolink autosave code codesample colorpicker contextmenu directionality emoticons fullscreen hr image imagetools insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
        ],
        toolbar: [
          'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
          'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
        ],
        nonbreaking_force_tab: true // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        // images_upload_handler: (blobInfo, success, failure) => {
        //   const formdata = new FormData()
        //   formdata.set('file', blobInfo.blob())
        //   // 上传到服务器后要改地址
        //   // 这个地址是我自己后台上传图片的地址，改成自己后台上传图片的地址http://localhost:8088/api/upload/img/
        //   axios
        //     .post('http://localhost:8088/api/upload/img/', formdata)
        //     .then((res) => {
        //       // 上传到服务器后要改地址
        //       // 这个地址是我图片映射路径http://localhost:8088/images/，可以用nginx
        //       success('http://localhost:8088/images/' + res.data)
        //     })
        //     .catch((res) => {
        //       failure('error')
        //     })
        // }
      }
      // value: this.curValue
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    // 动态传参
    curValue(newValue) {
      // console.log('22222222', newValue)
      this.value = newValue
    },
    // 读取输入框内的数据
    value(newValue) {
      // console.log(2222)
      this.$emit('input', newValue)
    }
  },
  // deactivated() {
  //   this.destroyTinymce()
  // },
  // destroyed() {
  //   this.destroyTinymce()
  // },
  mounted() {
    tinymce.init({})

    // setTimeout(() => {}, 200)
    this.oss = new Oss(this.stsToken, window)
    this.oss.__init__()
  },
  methods: {
    // destroyTinymce() {
    //   const tinymce = tinymce.get(this.tinymceId)
    //   if (this.fullscreen) {
    //     tinymce.execCommand('mceFullScreen')
    //   }
    //   if (tinymce) {
    //     tinymce.destroy()
    //   }
    // },
    handleUploadImg(param) {
      console.log(param)
      this.oss.__main__('activity', 'uploadImg', param).then((res) => {
        console.log(res)
        if (res.res.status === 200) {
          this.$message.success('上传成功')
          this.fileList = []
          console.log(this.tinymceId)
          tinymce
            .get(this.tinymceId)
            .insertContent(
              `<img class="wscnph" src="${
                res.res.requestUrls[0].split('?uploadId=')[0]
              }" >`
            )
          // this.contentAddForm.image = res.name
          // this.fileList = [
          //   {
          //     name: 'food.jpeg',
          //     url: res.name
          //   }
          // ]
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    }
  }
}
</script>
<style lang="scss" scoped>
.tox-tinymce-aux {
  z-index: 50000 !important;
}
.tinymce-container {
  position: relative;
  line-height: normal;
  z-index: 99999 !important;
}
.tox-dialog-wrap {
  z-index: 99999 !important;
}
.tinymce-container {
  ::v-deep {
    .mce-fullscreen {
      z-index: 99999 !important;
    }
  }
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}

.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}

.fullscreen .editor-custom-btn-container {
  z-index: 100000 !important;
  position: fixed;
}

.editor-upload-btn {
  display: inline-block;
}
</style>

